package dnl.ui.clipboard;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;

import org.apache.commons.lang.SystemUtils;

public class ClipboardUtils {

	private static ClipboardManager clipboardManager = new ClipboardManager();

	@SuppressWarnings("unchecked")
	public static Object getClipboardContents() {
		String result = "";
		Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
		// odd: the Object param of getContents is not currently used
		Transferable contents = clipboard.getContents(null);

		if (contents == null) {
			return result;
		}

		if (contents.isDataFlavorSupported(DataFlavor.imageFlavor)) {
			try {
				Image image = (Image) contents.getTransferData(DataFlavor.imageFlavor);
				return ImageContent.fromImage(image);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (contents.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
			try {
				java.util.List<File> files = (java.util.List<File>) contents
						.getTransferData(DataFlavor.javaFileListFlavor);
				return FileContent.fromFile(files.get(0));
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
			try {
				result = (String) contents.getTransferData(DataFlavor.stringFlavor);
			} catch (UnsupportedFlavorException ex) {
				ex.printStackTrace();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}

		return result;
	}

	public static void setClipboardContents(String aString) {
		StringSelection stringSelection = new StringSelection(aString);
		Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
		clipboard.setContents(stringSelection, clipboardManager);
	}

	public static void setClipboardContents(File f) {
		if (SystemUtils.IS_OS_UNIX) {

		} else {
			Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
			FileSelection fileSelection = new FileSelection(f);
			clipboard.setContents(fileSelection, clipboardManager);
		}
	}

	public static void setClipboardContents(Image image) {
		Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
		ImageSelection imageSelection = new ImageSelection(image);
		clipboard.setContents(imageSelection, clipboardManager);
	}
}
